package org.directfire.player.utils;

import java.io.IOException;
import org.directfire.player.ApplicationActivity;
import org.directfire.player.DirectFire;
import org.directfire.player.R;
import android.app.Notification;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.res.AssetFileDescriptor;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.support.v4.app.NotificationCompat;
import android.widget.Toast;
/**
 *   Copyright (C) 2012 Alexey Kostrjitskiy mailto:alex@ipss.net
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 *
 * $Id: NotificationUtils.java 35 2012-08-31 16:23:54Z alexeyvk@gmail.com $<br/>
 * $HeadURL: http://directfire.googlecode.com/svn/branches/0.1/DirectFireAndroid/src/org/directfire/player/utils/NotificationUtils.java $<br/><br/>
 *
 * Tool class for managing system notifications and sound notifications 
 */
public class NotificationUtils {
  //private static final String TAG = NotificationUtils.class.getSimpleName();
  private static NotificationUtils instance;

  private static Context context = DirectFire.getContext();
  private Notification notification=null;
  private PendingIntent pi=null; 

  /** sound for disconnection */
  public static final int SOUND_DISCONNECTED=0;
  /** sound for connection */
  public static final int SOUND_CONNECTED=1;
  
  
  private NotificationUtils(){
    //manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
    notification = null;
  	pi = PendingIntent.getActivity(context, 0,
        new Intent(context, ApplicationActivity.class),
        PendingIntent.FLAG_UPDATE_CURRENT);
  }

  public static NotificationUtils getInstance(){
    if(instance==null)
    	instance = new NotificationUtils();
    return instance;
  }
  
  public Notification create(String title, String message){
    //TODO: bug in setProgress()! temporary patched v4-support
    //http://code.google.com/p/android/issues/detail?id=36502
  	NotificationCompat.Builder nb = new NotificationCompat.Builder(context)
    	.setLargeIcon(getBitmapFromDrawableId(context, R.drawable.ic_launcher))
    	.setSmallIcon(R.drawable.ic_stat_example
    			)
  		.setContentTitle(title)
  		.setTicker(message)
  		.setContentText(message)
      .setContentIntent(pi)
      .setOngoing(true)
      .setWhen(System.currentTimeMillis());
      //.setDefaults(Notification.DEFAULT_ALL); // звук, вибро и диодный индикатор по умолчанию
    	//nb.setSound(Uri.parse("android.resource://" + context.getPackageName() + "/" + R.raw.new_track));
    	nb.setVibrate(new long[]{90,90,90,90});// two ticks
    notification = nb.build();
    return notification;
  }
  
  /**
   * This method returns a bitmap related to resource id.
   * 
   * @param context Context of calling activity
   * @param drawableId Resource ID of bitmap drawable
   * @return Bitmap whose resource id was passed to method.
   */
  public static Bitmap getBitmapFromDrawableId(Context context,int drawableId){
      Bitmap bitmap = null;
      try {
          BitmapDrawable drawable = (BitmapDrawable)context.getResources().getDrawable(drawableId);
          bitmap = drawable.getBitmap();

      } catch (Exception e) {
          e.printStackTrace();
      }
      return bitmap;
  }
  
  /** public interface to foreground sound notification */
  public void soundNotification(int what){
  	SoundNotify sn = new SoundNotify(what);
  	sn.start();
  }
  
  static public class SoundNotify extends Thread implements Runnable {
  	private int what=0;
  	private static MediaPlayer mp=null;
  	
  	public SoundNotify(int what){
  		this.what = what;
  		setName("MediaPlayer notification");
  	}
  	
  	public void run() {
  		if(mp!=null){
  			mp.stop();
  		}
  		AssetFileDescriptor afd=null;
    	switch(what){
  		 case SOUND_CONNECTED:
  			 afd = context.getResources().openRawResourceFd(R.raw.connection_repaired);
  			break;
  		 case SOUND_DISCONNECTED:
  			 afd = context.getResources().openRawResourceFd(R.raw.connection_failed);
  			break;
  		 default:
    	}
    	if(afd!=null){
    		try{
    			if(mp!=null){
    				mp.stop();
    				while(mp.isPlaying())
    					;
    				while(mp!=null)
    					;
    			}
	    		mp = new MediaPlayer();
	    		mp.setAudioStreamType(AudioManager.STREAM_NOTIFICATION);
	    		mp.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
	    		mp.prepare();
	    		AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
	    		int result = audioManager.requestAudioFocus(null, AudioManager.STREAM_ALARM,
	    				AudioManager.AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK);
	 			 	if (result != AudioManager.AUDIOFOCUS_REQUEST_GRANTED) 
	 			 		Toast.makeText(context, context.getResources().getString(R.string.trs_error_request_audiofocus_notify), Toast.LENGTH_LONG).show();
	 			 	else{
	 			 		mp.setOnCompletionListener(new OnCompletionListener() {
	 			 			public void onCompletion(MediaPlayer mediap) {
	 			 				mediap.stop();
	 			 				mediap.release();
	 			 				mp=null;
	 			 			}
	 			 		});
	 			 		mp.start();
	 			 	}
 			 	} catch (IllegalArgumentException e) {
					e.printStackTrace();
				} catch (IllegalStateException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
    	}
  	}
  }
}
